    //credit http://stackoverflow.com/a/8782422/52160
function dataURItoBlob(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
}

function supprA(id){
    $.ajax("/BlogD/resources/articles/"+id,
    {
        type:"DELETE",
        success: function(d){
            $("#article-"+id).slideUp('slow',function(){
                $(this).remove()
            });
        }
    });
    return false;
}

function lookArray(array){
    var monArraySeria = '';
                for (var i in array)
                {
                    /* On fais ce qu'on veux.. */
                    /* Exemple: */
                    // alert('Key: ' + i + "\r\nValeur: " + monArray[i]);
                    // ou:
                    monArraySeria += 'Key: ' + i + '; Valeur: ' + array[i] + "\r\n";
                }
                alert("lookarray:"+monArraySeria);
}
jQuery(document).ready(function($){
    
    /*$.get("resources/articles/",function(data){
        $("#list-article").prepend(hyperRenderItem(data));
    });*/
      var dropbox = document.querySelector("#dropbox");

    // init event handlers
    dropbox.addEventListener("dragenter", dragEnter, false);
    dropbox.addEventListener("dragexit", dragExit, false);
    dropbox.addEventListener("dragover", dragOver, false);
    dropbox.addEventListener("drop", drop, false);

function dragEnter(evt) {
    evt.stopPropagation();
    evt.preventDefault();
}

function dragExit(evt) {
    evt.stopPropagation();
    evt.preventDefault();
}

function dragOver(evt) {
    evt.stopPropagation();
    evt.preventDefault();
}

function drop(evt) {
  console.log("dans drop");
  
    evt.stopPropagation();
    evt.preventDefault();

    var files = evt.dataTransfer.files;
    var count = files.length;

    // Only call the handler if 1 or more files was dropped.
    if (count > 0)
        readFilesAndDisplayPreview(files);
}
  
  function readFilesAndDisplayPreview(files) {
    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match('image.*')) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement('span');
          span.innerHTML = ['<img class="thumb" src="', e.target.result,
                            '" title="', escape(theFile.name), '"/>'].join('');
          document.getElementById('list').insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    readFilesAndDisplayPreview(files);
  }
function hyperRenderItem(d){
    var html="";
//    alert($(d).find('articles').text());
    $(d).find('article').each(function(){
        html += superRenderItem(this);
        
        
    })
    
   return html;
}
function superRenderItem(d)
    {
        var id = $(d).find('article>id').text();
        var titre = $(d).find('titre').text();
        var contenu = $(d).find('contenu').text();
        var myDate = new Date( $(d).find('dateCreation').text() );
        var strDate = "";
        strDate += myDate.getUTCDate()+"/"+myDate.getMonth()+"/"+myDate.getFullYear();
        strDate += " à "+myDate.getHours()+":"+myDate.getMinutes();
        var html ="";
        $(d).find('lesimages').each(function() {
           
             html+= '<p><img class="thumb" src="'+$(this).find('chemin').text()+'"/></p>';
         });
        var myvar = "<div class='well well-small' id='article-"+id+"'>";
        myvar+=     "<div class='image span2' style='border-right: 1px solid #fff'>"+html+"</div>";
        myvar+=     "<div class='span5'><p class='pull-right' style='margin: 10px;'>Article publi&eacute; le "+strDate+"</p><h4>"+titre+"</h4>"
        myvar+=     "<p class='content clearfix'>"+contenu+"</p>\n";
        myvar+=     "<p><a onclick='supprA("+id+")' class='btn btn-primary pull-right'>Supprimer</a></div>";
        myvar+=     "<div class='clearfix'></div></div>";
        return myvar;
    }

function renderItem(id, titre, content, date,tabimg,nbr)
    {
        var myDate = new Date( date );
        var strDate = "";
        strDate += myDate.getUTCDate()+"/"+myDate.getMonth()+"/"+myDate.getFullYear();
        strDate += " à "+myDate.getHours()+":"+myDate.getMinutes();
        var html ="";
        
        for(var i= 0; i < nbr; i++)
        {
             html+= '<p><img class="thumb" src="'+tabimg[i]+'"></p>';
         }
        return "<div class='well well-small' id='article-"+id+"'>\
                <h2>"+titre+"</h2></a>\
                <p class='content'>"+content+"</p>\
                <div class='image'>"+html+"</div>\
                    <div class='clearfix'></div>\
                </div>";
    }
    
    // supprimer un article
    $(".delete").click(function(){

        var id = $(this).attr("rel");
        
        alert("id");  
        console.log("suppression d'un article lien:"+id);

        $.ajax(id,
        {
            type:"DELETE",
            success: function(d){
                $("#article-"+d).slideUp('slow',function(){
                    $(this).remove()
                    });
            }
        });
        return false;
    });
    //affiche la liste des articles
    $("#btnarticles").click(function(){
        $.get("resources/articles/",function(data){
            $("#list-article").empty();
            //$("#form-article").hide();
            $("#btnform").show();
            $("#list-article").prepend(hyperRenderItem(data));  
        });
    });
    $("#btnform").click(function(){
        $("#list-article").empty();
    });
    //creer une form
     $("#publier").click(function(){
       
        var data = new FormData();  
        data.append('titre', $("#titre").val());  
        data.append('contenu', $("#content").val());
       
        jQuery.each($('#list img'), function(i, img) {
            image= dataURItoBlob(img.src);
       
            // img.src correspond au dataURL des images  
            data.append('image-'+i, image);
           
           
           
        });  
         
         $.ajax({  
            url: 'resources/articles/ajoutfull',data: data,cache: false,contentType: false,processData: false,  
            type: 'POST',  
            success: function(data){  
                $("#form-article").each(function(){this.reset();});
                $('#list').empty();
                $.get(data,function(d){$("#list-article").prepend(superRenderItem(d));  
                });
//                    
//                    alert(renderItem(article[0], article[1], article[2], article[3].split("%"),  article[3].split("%").length));
//                   $("#list-article").prepend(renderItem(article[0], article[1], article[2], article[3].split("%")));  
                 
//            });
           
            }  
        });  
         
    });
   
   
   
   
});



